<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 火车票订票系统</title>
    
    <!-- 引入样式 -->
    <link rel="stylesheet" href="css/login-modal.css">
    <link rel="stylesheet" href="css/profile.css">
</head>
<body>
    <!-- 顶部导航栏 -->
    <header class="main-header">
        <div class="header-content">
            <a href="index.html" class="logo">🚄 火车票订票系统</a>
            <div class="nav-actions">
                <a href="index.html" class="back-btn">🏠 返回首页</a>
            </div>
        </div>
    </header>

    <div class="container">
        <!-- 页面头部 -->
        <div class="profile-header">
            <div class="header-gradient-bg"></div>
            <div class="header-content-inner">
                <h1>👤 个人中心</h1>
                <p>管理您的个人信息和账户设置</p>
                <div class="profile-stats">
                    <div class="stat-item">
                        <span class="stat-number" id="loginCount">-</span>
                        <span class="stat-label">登录次数</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-number" id="memberDays">-</span>
                        <span class="stat-label">注册天数</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-number" id="orderCount">-</span>
                        <span class="stat-label">订单总数</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 主要内容区域 -->
        <div class="profile-content">
            <!-- 侧边栏 - 用户信息 -->
            <div class="profile-sidebar">
                <div class="sidebar-header">
                    <h3>个人信息</h3>
                    <div class="user-status">
                        <span class="status-indicator online"></span>
                        <span class="status-text">在线</span>
                    </div>
                </div>
                
                <!-- 头像区域 -->
                <div class="avatar-section">
                    <div class="avatar-wrapper">
                        <img id="userAvatar" class="avatar-img" src="images/default-avatar.png" alt="用户头像" 
                             onerror="this.src=''" />
                        <div class="avatar-overlay" onclick="changeAvatar()">
                            <span class="upload-icon">📷</span>
                        </div>
                        <div class="avatar-level">
                            <span class="level-badge">Lv.1</span>
                        </div>
                    </div>
                    <button class="btn avatar-change-btn" onclick="changeAvatar()">
                        <span class="btn-icon">📸</span>
                        更换头像
                    </button>
                </div>
                
                <!-- 用户信息列表 -->
                <div class="user-info-container">
                    <h4 class="section-title">基础信息</h4>
                    <ul class="user-info">
                        <li class="info-item">
                            <div class="info-content">
                                <span class="info-label">👤 用户名称</span>
                                <span class="info-value" id="userName">未登录</span>
                            </div>
                        </li>
                        <li class="info-item">
                            <div class="info-content">
                                <span class="info-label">📱 手机号码</span>
                                <span class="info-value" id="phoneNumber">-</span>
                            </div>
                        </li>
                        <li class="info-item">
                            <div class="info-content">
                                <span class="info-label">📧 用户邮箱</span>
                                <span class="info-value" id="userEmail">-</span>
                            </div>
                        </li>
                        <li class="info-item">
                            <div class="info-content">
                                <span class="info-label">📅 注册时间</span>
                                <span class="info-value" id="createTime">-</span>
                            </div>
                        </li>
                    </ul>
                </div>

                <!-- 快速操作 -->
                <div class="quick-actions">
                    <h4 class="section-title">快速操作</h4>
                    <div class="action-buttons">
                        <button class="action-btn" onclick="window.location.href='index.html'">
                            <span class="action-icon">🏠</span>
                            返回首页
                        </button>
                        <button class="action-btn" onclick="HeroLoginModal.showLogoutConfirm()">
                            <span class="action-icon">🚪</span>
                            退出登录
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 主要内容区域 -->
            <div class="profile-main">
                <div class="main-header">
                    <h3>账户设置</h3>
                    <p>管理您的个人资料和账户安全</p>
                </div>
                
                <!-- 标签页 -->
                <div class="tabs">
                    <button class="tab-btn active" onclick="switchTab('userinfo')">
                        <span class="tab-icon">👤</span>
                        基本资料
                    </button>
                    <button class="tab-btn" onclick="switchTab('resetpwd')">
                        <span class="tab-icon">🔒</span>
                        修改密码
                    </button>
                </div>
                
                <!-- 基本资料表单 -->
                <div id="userinfo" class="tab-content active">
                    <div class="form-section">
                        <div class="form-section-header">
                            <h4>📝 个人信息</h4>
                            <p>更新您的基本个人资料</p>
                        </div>
                        
                        <form id="userInfoForm" class="modern-form">
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="nickName" class="form-label">
                                        <span class="label-icon">👤</span>
                                        用户昵称 *
                                    </label>
                                    <input type="text" id="nickName" class="form-input" placeholder="请输入用户昵称" maxlength="30" required>
                                    <div id="nickNameError" class="error-msg" style="display: none;"></div>
                                </div>
                                
                                <div class="form-group">
                                    <label for="phoneForm" class="form-label">
                                        <span class="label-icon">📱</span>
                                        手机号码 *
                                    </label>
                                    <input type="tel" id="phoneForm" class="form-input" placeholder="请输入手机号码" maxlength="11" required>
                                    <div id="phoneError" class="error-msg" style="display: none;"></div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="emailForm" class="form-label">
                                    <span class="label-icon">📧</span>
                                    邮箱地址 *
                                </label>
                                <input type="email" id="emailForm" class="form-input" placeholder="请输入邮箱地址" maxlength="50" required>
                                <div id="emailError" class="error-msg" style="display: none;"></div>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">
                                    <span class="label-icon">⚧</span>
                                    性别
                                </label>
                                <div class="radio-group modern-radio">
                                    <label class="radio-item">
                                        <input type="radio" name="sex" value="0" checked>
                                        <span class="radio-custom"></span>
                                        <span class="radio-label">👨 男</span>
                                    </label>
                                    <label class="radio-item">
                                        <input type="radio" name="sex" value="1">
                                        <span class="radio-custom"></span>
                                        <span class="radio-label">👩 女</span>
                                    </label>
                                </div>
                            </div>
                            
                            <div class="form-actions">
                                <button type="button" class="btn btn-primary" onclick="saveUserInfo()">
                                    <span class="btn-icon">💾</span>
                                    保存更改
                                </button>
                                <button type="button" class="btn btn-secondary" onclick="resetForm()">
                                    <span class="btn-icon">🔄</span>
                                    重置
                                </button>
                            </div>
                            
                            <div id="userInfoMsg" class="form-message"></div>
                        </form>
                    </div>
                </div>
                
                <!-- 修改密码表单 -->
                <div id="resetpwd" class="tab-content">
                    <div class="form-section">
                        <div class="form-section-header">
                            <h4>🔐 修改密码</h4>
                            <p>更新您的登录密码，确保账户安全</p>
                        </div>
                        
                        <form id="resetPwdForm" class="modern-form">
                            <div class="form-group">
                                <label for="oldPassword" class="form-label">
                                    <span class="label-icon">🔑</span>
                                    当前密码 *
                                </label>
                                <input type="password" id="oldPassword" class="form-input" placeholder="请输入当前密码" required>
                                <div id="oldPwdError" class="error-msg" style="display: none;"></div>
                            </div>
                            
                            <div class="form-group">
                                <label for="newPassword" class="form-label">
                                    <span class="label-icon">🔒</span>
                                    新密码 *
                                </label>
                                <input type="password" id="newPassword" class="form-input" placeholder="请输入新密码(6-20位)" required>
                                <div class="password-strength">
                                    <div class="strength-indicator">
                                        <div class="strength-bar" id="strengthBar"></div>
                                    </div>
                                    <span class="strength-text" id="strengthText">密码强度</span>
                                </div>
                                <div id="newPwdError" class="error-msg" style="display: none;"></div>
                            </div>
                            
                            <div class="form-group">
                                <label for="confirmPassword" class="form-label">
                                    <span class="label-icon">✅</span>
                                    确认新密码 *
                                </label>
                                <input type="password" id="confirmPassword" class="form-input" placeholder="请确认新密码" required>
                                <div id="confirmPwdError" class="error-msg" style="display: none;"></div>
                            </div>
                            
                            <div class="password-tips">
                                <h5>密码安全建议：</h5>
                                <ul>
                                    <li>使用至少8个字符</li>
                                    <li>包含大小写字母、数字和特殊符号</li>
                                    <li>避免使用常见词汇或个人信息</li>
                                    <li>定期更换密码</li>
                                </ul>
                            </div>
                            
                            <div class="form-actions">
                                <button type="button" class="btn btn-primary" onclick="changePassword()">
                                    <span class="btn-icon">🔐</span>
                                    更新密码
                                </button>
                                <button type="button" class="btn btn-danger" onclick="document.getElementById('resetPwdForm').reset()">
                                    <span class="btn-icon">🗑️</span>
                                    清空
                                </button>
                            </div>
                            
                            <div id="resetPwdMsg" class="form-message"></div>
                        </form>
                    </div>
                </div>

                <!-- 安全设置 -->
                <div id="security" class="tab-content">
                    <div class="form-section">
                        <div class="form-section-header">
                            <h4>🛡️ 安全设置</h4>
                            <p>管理您的账户安全选项</p>
                        </div>
                        
                        <div class="security-options">
                            <div class="security-item">
                                <div class="security-info">
                                    <h5>🔔 登录通知</h5>
                                    <p>当有新设备登录时发送通知</p>
                                </div>
                                <label class="toggle-switch">
                                    <input type="checkbox" id="loginNotification" checked>
                                    <span class="toggle-slider"></span>
                                </label>
                            </div>
                            
                            <div class="security-item">
                                <div class="security-info">
                                    <h5>📱 双重认证</h5>
                                    <p>使用手机验证码增强账户安全</p>
                                </div>
                                <label class="toggle-switch">
                                    <input type="checkbox" id="twoFactorAuth">
                                    <span class="toggle-slider"></span>
                                </label>
                            </div>
                            
                            <div class="security-item">
                                <div class="security-info">
                                    <h5>🕒 自动登出</h5>
                                    <p>长时间不活动时自动登出</p>
                                </div>
                                <select class="form-input security-select" id="autoLogoutTime">
                                    <option value="30">30分钟</option>
                                    <option value="60" selected>1小时</option>
                                    <option value="120">2小时</option>
                                    <option value="240">4小时</option>
                                </select>
                            </div>
                            
                            <div class="security-item danger-zone">
                                <div class="security-info">
                                    <h5>⚠️ 危险操作</h5>
                                    <p>请谨慎操作以下功能</p>
                                </div>
                                <div class="danger-actions">
                                    <button class="btn btn-warning" onclick="showConfirm('清除所有会话', '这将登出所有设备上的会话，确定继续吗？', () => {})">
                                        🚪 登出所有设备
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 返回按钮 -->
        <div style="text-align: center; margin-top: 30px;">
            <button class="btn secondary" onclick="goBack()">返回上一页</button>
        </div>
    </div>
    
    <!-- 头像上传模态框 -->
    <div id="avatarModal" class="modal-overlay">
        <div class="modal avatar-upload-modal">
            <div class="modal-header">
                <h3>更换头像</h3>
                <button class="modal-close" onclick="closeModal('avatarModal')">&times;</button>
            </div>
            <div class="modal-body">
                <div class="avatar-preview">
                    <img id="avatarPreview" src="images/profile.jpg" alt="头像预览">
                </div>
                <div class="file-upload-area" id="fileUploadArea">
                    <div class="upload-icon">📸</div>
                    <p style="margin: 0; color: var(--text-secondary);">点击或拖拽选择图片</p>
                    <small style="color: var(--text-secondary);">支持 JPG、PNG 格式，最大 5MB</small>
                    <input type="file" id="avatarFileInput" accept="image/*" style="display: none;">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn secondary" onclick="closeModal('avatarModal')">取消</button>
                <button class="btn" id="uploadAvatarBtn" onclick="confirmUploadAvatar()" disabled>上传头像</button>
            </div>
        </div>
    </div>
    
    <!-- 确认对话框 -->
    <div id="confirmModal" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 id="confirmTitle">确认操作</h3>
                <button class="modal-close" onclick="closeModal('confirmModal')">&times;</button>
            </div>
            <div class="modal-body">
                <div class="confirm-dialog">
                    <div id="confirmIcon" class="confirm-icon warning">⚠️</div>
                    <p id="confirmMessage">确定要执行此操作吗？</p>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn secondary" onclick="closeModal('confirmModal')">取消</button>
                <button class="btn" id="confirmBtn" onclick="handleConfirm()">确定</button>
            </div>
        </div>
    </div>
    
    <!-- 通知容器 -->
    <div id="notificationContainer"></div>
    
    <!-- 引入脚本 -->
    <script src="js/request.js"></script>
    <script src="js/auth.js"></script>
    <script src="js/common.js"></script>
    <script src="js/profile.js"></script>
    
    <script>
        // 当前用户数据
        let currentUser = null;
        let selectedFile = null;
        let currentConfirmCallback = null;
        
        // 模态框管理
        const ModalManager = {
            open(modalId) {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.classList.add('show');
                    document.body.style.overflow = 'hidden';
                }
            },
            
            close(modalId) {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.classList.remove('show');
                    document.body.style.overflow = '';
                    
                    // 清理
                    if (modalId === 'avatarModal') {
                        selectedFile = null;
                        document.getElementById('uploadAvatarBtn').disabled = true;
                    }
                }
            },
            
            closeAll() {
                const modals = document.querySelectorAll('.modal-overlay');
                modals.forEach(modal => {
                    modal.classList.remove('show');
                });
                document.body.style.overflow = '';
            }
        };
        
        // 通知管理
        const NotificationManager = {
            show(message, type = 'info', duration = 4000) {
                const container = document.getElementById('notificationContainer');
                const notification = document.createElement('div');
                notification.className = `notification ${type}`;
                notification.innerHTML = `
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="font-size: 20px;">
                            ${type === 'success' ? '✅' : type === 'warning' ? '⚠️' : type === 'error' ? '❌' : 'ℹ️'}
                        </div>
                        <div style="flex: 1;">
                            <div style="font-weight: 600; margin-bottom: 4px;">
                                ${type === 'success' ? '成功' : type === 'warning' ? '警告' : type === 'error' ? '错误' : '提示'}
                            </div>
                            <div style="color: var(--text-secondary);">${message}</div>
                        </div>
                    </div>
                `;
                
                container.appendChild(notification);
                
                // 显示动画
                setTimeout(() => notification.classList.add('show'), 100);
                
                // 自动隐藏
                setTimeout(() => {
                    notification.classList.remove('show');
                    setTimeout(() => {
                        if (notification.parentNode) {
                            notification.parentNode.removeChild(notification);
                        }
                    }, 300);
                }, duration);
            }
        };
        
        // 确认对话框
        function showConfirm(title, message, callback, type = 'warning') {
            document.getElementById('confirmTitle').textContent = title;
            document.getElementById('confirmMessage').textContent = message;
            
            const iconElement = document.getElementById('confirmIcon');
            iconElement.className = `confirm-icon ${type}`;
            iconElement.textContent = type === 'warning' ? '⚠️' : 
                                    type === 'success' ? '✅' : 
                                    type === 'error' ? '❌' : 'ℹ️';
            
            currentConfirmCallback = callback;
            ModalManager.open('confirmModal');
        }
        
        // 处理确认
        function handleConfirm() {
            if (currentConfirmCallback) {
                currentConfirmCallback();
                currentConfirmCallback = null;
            }
            ModalManager.close('confirmModal');
        }
        
        // 关闭模态框
        function closeModal(modalId) {
            ModalManager.close(modalId);
        }
        
        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkLoginAndLoad();
        });
        
        // 检查登录状态并加载用户信息
        function checkLoginAndLoad() {
            if (!HeroAuth.isLoggedIn()) {
                NotificationManager.show('请先登录后访问个人中心', 'warning');
                // 可以跳转到登录页面或显示登录模态框
                setTimeout(() => {
                    window.location.href = 'demo-login.html';
                }, 1500);
                return;
            }
            
            // 加载用户信息
            loadUserInfo();
        }
        
        // 加载用户信息
        function loadUserInfo() {
            HeroProfile.getUserProfile()
                .then(data => {
                    if (data && data.user) {
                        currentUser = data.user;
                        displayUserInfo(data);
                        fillUserForm(data.user);
                        updateProfileStats();
                    } else {
                        // 如果没有获取到数据，尝试使用原有方法
                        return HeroAuth.getInfo();
                    }
                })
                .then(data => {
                    if (data && data.user && !currentUser) {
                        currentUser = data.user;
                        displayUserInfo(data);
                        fillUserForm(data.user);
                        updateProfileStats();
                    }
                })
                .catch(error => {
                    console.error('获取用户信息失败:', error);
                    NotificationManager.show('获取用户信息失败: ' + error.message, 'error');
                });
        }
        
        // 显示用户信息
        function displayUserInfo(data) {
            const user = data.user;
            
            document.getElementById('userName').textContent = user.userName || '未知用户';
            document.getElementById('phoneNumber').textContent = user.phonenumber || '-';
            document.getElementById('userEmail').textContent = user.email || '-';
            document.getElementById('createTime').textContent = HeroProfile.formatDate(user.createTime);
            
            // 设置头像
            if (user.avatar) {
                document.getElementById('userAvatar').src = user.avatar;
            }
        }
        
        // 填充表单数据
        function fillUserForm(user) {
            document.getElementById('nickName').value = user.nickName || '';
            document.getElementById('phoneForm').value = user.phonenumber || '';
            document.getElementById('emailForm').value = user.email || '';
            
            // 设置性别
            if (user.sex !== undefined) {
                const sexRadio = document.querySelector(`input[name="sex"][value="${user.sex}"]`);
                if (sexRadio) {
                    sexRadio.checked = true;
                }
            }
        }
        
        // 标签页切换
        function switchTab(tabName) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签按钮的激活状态
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // 显示选中的标签内容
            document.getElementById(tabName).classList.add('active');
            
            // 激活对应的标签按钮
            event.target.classList.add('active');
        }

        // 密码强度检测
        function checkPasswordStrength(password) {
            let strength = 0;
            let text = '密码强度';
            
            // 长度检查
            if (password.length >= 8) strength += 1;
            if (password.length >= 12) strength += 1;
            
            // 字符类型检查
            if (/[a-z]/.test(password)) strength += 1;
            if (/[A-Z]/.test(password)) strength += 1;
            if (/[0-9]/.test(password)) strength += 1;
            if (/[^A-Za-z0-9]/.test(password)) strength += 1;
            
            const strengthBar = document.getElementById('strengthBar');
            const strengthText = document.getElementById('strengthText');
            
            if (strengthBar && strengthText) {
                strengthBar.className = 'strength-bar';
                
                if (strength < 3) {
                    strengthBar.classList.add('weak');
                    text = '弱';
                } else if (strength < 5) {
                    strengthBar.classList.add('medium');
                    text = '中等';
                } else {
                    strengthBar.classList.add('strong');
                    text = '强';
                }
                
                strengthText.textContent = text;
            }
        }

        // 统计数据更新
        function updateProfileStats() {
            // 模拟数据，实际应从后端获取
            const stats = {
                loginCount: Math.floor(Math.random() * 100) + 50,
                memberDays: Math.floor((Date.now() - new Date(currentUser?.createTime || Date.now() - 365*24*60*60*1000)) / (1000 * 60 * 60 * 24)),
                orderCount: Math.floor(Math.random() * 20) + 5
            };
            
            document.getElementById('loginCount').textContent = stats.loginCount;
            document.getElementById('memberDays').textContent = stats.memberDays;
            document.getElementById('orderCount').textContent = stats.orderCount;
        }
        
        // 表单验证
        function validateUserInfo() {
            const formData = {
                nickName: document.getElementById('nickName').value.trim(),
                phonenumber: document.getElementById('phoneForm').value.trim(),
                email: document.getElementById('emailForm').value.trim()
            };
            
            const validation = HeroProfile.validateUserForm(formData);
            
            // 清除所有错误
            hideFieldError('nickNameError');
            hideFieldError('phoneError');
            hideFieldError('emailError');
            
            // 显示错误信息
            if (!validation.isValid) {
                if (validation.errors.nickName) {
                    showFieldError('nickNameError', validation.errors.nickName);
                }
                if (validation.errors.phonenumber) {
                    showFieldError('phoneError', validation.errors.phonenumber);
                }
                if (validation.errors.email) {
                    showFieldError('emailError', validation.errors.email);
                }
            }
            
            return validation.isValid;
        }
        
        // 验证密码表单
        function validatePassword() {
            const formData = {
                oldPassword: document.getElementById('oldPassword').value.trim(),
                newPassword: document.getElementById('newPassword').value.trim(),
                confirmPassword: document.getElementById('confirmPassword').value.trim()
            };
            
            const validation = HeroProfile.validatePasswordForm(formData);
            
            // 清除所有错误
            hideFieldError('oldPwdError');
            hideFieldError('newPwdError');
            hideFieldError('confirmPwdError');
            
            // 显示错误信息
            if (!validation.isValid) {
                if (validation.errors.oldPassword) {
                    showFieldError('oldPwdError', validation.errors.oldPassword);
                }
                if (validation.errors.newPassword) {
                    showFieldError('newPwdError', validation.errors.newPassword);
                }
                if (validation.errors.confirmPassword) {
                    showFieldError('confirmPwdError', validation.errors.confirmPassword);
                }
            }
            
            return validation.isValid;
        }
        
        // 显示字段错误
        function showFieldError(errorId, message) {
            const errorElement = document.getElementById(errorId);
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }
        
        // 隐藏字段错误
        function hideFieldError(errorId) {
            document.getElementById(errorId).style.display = 'none';
        }
        
        // 显示消息
        function showMessage(elementId, message, type = 'success') {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.className = type === 'success' ? 'success-msg' : 'error-msg';
            element.style.display = 'block';
            
            setTimeout(() => {
                element.style.display = 'none';
            }, 3000);
        }
        
        // 保存用户信息
        function saveUserInfo() {
            if (!validateUserInfo()) {
                return;
            }
            
            const saveBtn = document.querySelector('button[onclick="saveUserInfo()"]');
            saveBtn.classList.add('loading');
            saveBtn.disabled = true;
            
            const formData = {
                nickName: document.getElementById('nickName').value.trim(),
                phonenumber: document.getElementById('phoneForm').value.trim(),
                email: document.getElementById('emailForm').value.trim(),
                sex: document.querySelector('input[name="sex"]:checked').value
            };
            
            // 调用真实API保存用户信息
            HeroProfile.updateUserProfile(formData)
                .then(response => {
                    // 更新当前用户数据
                    if (currentUser) {
                        currentUser.nickName = formData.nickName;
                        currentUser.phonenumber = formData.phonenumber;
                        currentUser.email = formData.email;
                        currentUser.sex = formData.sex;
                        
                        // 更新侧边栏显示
                        document.getElementById('phoneNumber').textContent = formData.phonenumber;
                        document.getElementById('userEmail').textContent = formData.email;
                    }
                    
                    showMessage('userInfoMsg', '保存成功!', 'success');
                    NotificationManager.show('个人信息保存成功！', 'success');
                })
                .catch(error => {
                    console.error('保存用户信息失败:', error);
                    showMessage('userInfoMsg', '保存失败: ' + error.message, 'error');
                    NotificationManager.show('保存失败: ' + error.message, 'error');
                })
                .finally(() => {
                    saveBtn.classList.remove('loading');
                    saveBtn.disabled = false;
                });
        }
        
        // 修改密码
        function changePassword() {
            if (!validatePassword()) {
                return;
            }
            
            showConfirm(
                '确认修改密码',
                '修改密码后需要重新登录，确定要继续吗？',
                () => {
                    const saveBtn = document.querySelector('button[onclick="changePassword()"]');
                    saveBtn.classList.add('loading');
                    saveBtn.disabled = true;
                    
                    const oldPassword = document.getElementById('oldPassword').value.trim();
                    const newPassword = document.getElementById('newPassword').value.trim();
                    
                    // 调用真实API修改密码
                    HeroProfile.updateUserPassword(oldPassword, newPassword)
                        .then(response => {
                            // 清空表单
                            document.getElementById('resetPwdForm').reset();
                            
                            showMessage('resetPwdMsg', '密码修改成功!', 'success');
                            NotificationManager.show('密码修改成功！', 'success');
                        })
                        .catch(error => {
                            console.error('修改密码失败:', error);
                            showMessage('resetPwdMsg', '修改失败: ' + error.message, 'error');
                            NotificationManager.show('修改失败: ' + error.message, 'error');
                        })
                        .finally(() => {
                            saveBtn.classList.remove('loading');
                            saveBtn.disabled = false;
                        });
                },
                'warning'
            );
        }
        
        // 重置表单
        function resetForm() {
            if (currentUser) {
                fillUserForm(currentUser);
            }
            
            // 清除所有错误信息
            document.querySelectorAll('.error-msg').forEach(error => {
                error.style.display = 'none';
            });
            
            NotificationManager.show('表单已重置', 'info');
        }
        
        // 更换头像
        function changeAvatar() {
            // 设置预览图片为当前头像
            const currentAvatarSrc = document.getElementById('userAvatar').src;
            document.getElementById('avatarPreview').src = currentAvatarSrc;
            
            // 显示模态框
            ModalManager.open('avatarModal');
        }
        
        // 确认上传头像
        function confirmUploadAvatar() {
            if (!selectedFile) {
                NotificationManager.show('请先选择要上传的图片', 'warning');
                return;
            }
            
            const uploadBtn = document.getElementById('uploadAvatarBtn');
            uploadBtn.classList.add('loading');
            uploadBtn.disabled = true;
            
            HeroProfile.uploadAvatar(selectedFile)
                .then(response => {
                    // 更新头像显示
                    if (response.imgUrl) {
                        const avatarUrl = response.imgUrl.startsWith('http') ? 
                            response.imgUrl : 
                            (window.location.origin + response.imgUrl);
                        document.getElementById('userAvatar').src = avatarUrl;
                        
                        // 更新当前用户数据
                        if (currentUser) {
                            currentUser.avatar = avatarUrl;
                        }
                    }
                    
                    NotificationManager.show('头像上传成功！', 'success');
                    ModalManager.close('avatarModal');
                })
                .catch(error => {
                    console.error('头像上传失败:', error);
                    NotificationManager.show('头像上传失败: ' + error.message, 'error');
                })
                .finally(() => {
                    uploadBtn.classList.remove('loading');
                    uploadBtn.disabled = false;
                });
        }
        
        // 返回上一页
        function goBack() {
            if (document.referrer) {
                history.back();
            } else {
                window.location.href = 'demo-login.html';
            }
        }
        
        // 监听登录状态变化
        document.addEventListener('hero:logoutSuccess', function() {
            NotificationManager.show('您已注销，即将跳转到登录页面', 'info');
            setTimeout(() => {
                window.location.href = 'demo-login.html';
            }, 1500);
        });
        
        // 监听个人中心模块就绪事件
        document.addEventListener('hero:profileReady', function(e) {
            console.log('个人中心模块已就绪:', e.detail);
        });
        
        // 初始化文件上传功能
        document.addEventListener('DOMContentLoaded', function() {
            const fileUploadArea = document.getElementById('fileUploadArea');
            const fileInput = document.getElementById('avatarFileInput');
            const uploadBtn = document.getElementById('uploadAvatarBtn');
            
            // 点击上传区域
            fileUploadArea.addEventListener('click', () => {
                fileInput.click();
            });
            
            // 文件选择
            fileInput.addEventListener('change', handleFileSelect);
            
            // 密码强度检测
            const newPasswordInput = document.getElementById('newPassword');
            if (newPasswordInput) {
                newPasswordInput.addEventListener('input', function() {
                    checkPasswordStrength(this.value);
                });
            }
            
            // 拖拽功能
            fileUploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                fileUploadArea.classList.add('dragover');
            });
            
            fileUploadArea.addEventListener('dragleave', (e) => {
                e.preventDefault();
                fileUploadArea.classList.remove('dragover');
            });
            
            fileUploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                fileUploadArea.classList.remove('dragover');
                
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    handleFile(files[0]);
                }
            });
            
            // ESC键关闭模态框
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') {
                    ModalManager.closeAll();
                }
            });
            
            // 点击遮罩层关闭模态框
            document.querySelectorAll('.modal-overlay').forEach(overlay => {
                overlay.addEventListener('click', (e) => {
                    if (e.target === overlay) {
                        ModalManager.close(overlay.id);
                    }
                });
            });
        });
        
        // 处理文件选择
        function handleFileSelect(e) {
            const file = e.target.files[0];
            if (file) {
                handleFile(file);
            }
        }
        
        // 处理文件
        function handleFile(file) {
            try {
                // 验证文件
                if (!file.type.startsWith('image/')) {
                    NotificationManager.show('请选择图片文件', 'warning');
                    return;
                }
                
                if (file.size > 5 * 1024 * 1024) {
                    NotificationManager.show('图片大小不能超过 5MB', 'warning');
                    return;
                }
                
                // 预览图片
                const reader = new FileReader();
                reader.onload = (e) => {
                    document.getElementById('avatarPreview').src = e.target.result;
                    selectedFile = file;
                    document.getElementById('uploadAvatarBtn').disabled = false;
                };
                reader.readAsDataURL(file);
                
            } catch (error) {
                NotificationManager.show('文件处理失败: ' + error.message, 'error');
            }
        }
        
        // 页面加载动画
        document.addEventListener('DOMContentLoaded', function() {
            // 添加页面加载动画
            const elements = document.querySelectorAll('.profile-sidebar, .profile-main, .user-info li');
            elements.forEach((element, index) => {
                element.style.opacity = '0';
                element.style.transform = 'translateY(20px)';
                
                setTimeout(() => {
                    element.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
                    element.style.opacity = '1';
                    element.style.transform = 'translateY(0)';
                }, index * 100);
            });
        });
    </script>
</body>
</html>